<?php

function createNoncestr($length = 32) {
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str ="";
    for ( $i = 0; $i < $length; $i++ )  {
        $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
}

function access_token(){		//获取access_token
	if(!S('access_token')){
		$appid = C('appid');
		$appsectrt = C('appsecret');
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsectrt;
		//echo $url;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$output = curl_exec($ch);
		curl_close($ch);
		$arr = json_decode($output,true);
		//dump($arr);
		S('access_token',$arr['access_token'],7000);
	}
	//dump(S('access_token'));
	return S('access_token');
}

function jsapi_ticket(){
	if(!S('jsapi_ticket')){
		$appid = C('appid');
		$appsectrt = C('appsecret');
		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".access_token()."&type=jsapi";
		//echo $url;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$output = curl_exec($ch);
		curl_close($ch);
		$arr = json_decode($output,true);
		//dump($arr);
		//$arr2['time'] = time();
		//$arr2['key'] = $arr['ticket'];
		S('jsapi_ticket',$arr['ticket'],7000);
	}
	//dump(S('jsapi_ticket'));
	return S('jsapi_ticket');
}

/**
 * 	作用：格式化参数，签名过程需要使用
 */
function formatBizQueryParaMap($paraMap, $urlencode) {
    $buff = "";
    ksort($paraMap);
    foreach ($paraMap as $k => $v)
    {
        if($urlencode)
        {
           $v = urlencode($v);
        }
        //$buff .= strtolower($k) . "=" . $v . "&";
        $buff .= $k . "=" . $v . "&";
    }
    $reqPar;
    if (strlen($buff) > 0)
    {
        $reqPar = substr($buff, 0, strlen($buff)-1);
    }
    return $reqPar;
}

function signature() {
	$Obj['jsapi_ticket'] = jsapi_ticket();
	$Obj['noncestr'] = createNoncestr();
	$Obj['url'] = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	$Obj['timestamp'] = time();

	foreach ($Obj as $k => $v){
		$Parameters[$k] = $v;
	}
	//签名步骤一：按字典序排序参数
	ksort($Parameters);
	$String = formatBizQueryParaMap($Parameters, false);
	//echo '【string1】'.$String.'</br>';
	//签名步骤二：在string后加入KEY
	//$String = $String."&key=".C('mch_key');
	//echo "【string2】".$String."</br>";
	//签名步骤三：MD5加密
	$String = sha1($String);
	//echo "【string3】 ".$String."</br>";
	//签名步骤四：所有字符转为大写
	//$Obj['signature'] = strtoupper($String);
	$Obj['signature'] = $String;


	return $Obj;
}

function curl($url,$post=NULL) {

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	if(stripos($url,"https://")!==FALSE){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	if(isset($post)){	// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	}

	$output = curl_exec($ch);
	curl_close($ch);

	return $output;

}

/**
 * 微信api不支持中文转义的json结构
 * @param $arr
 * @return string
 */
function json_encode2($arr) {
    $parts = array ();
    $is_list = false;
    //Find out if the given array is a numerical array
    $keys = array_keys ( $arr );
    $max_length = count ( $arr ) - 1;
    if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
        $is_list = true;
        for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
            if ($i != $keys [$i]) { //A key fails at position check.
                $is_list = false; //It is an associative array.
                break;
            }
        }
    }
    foreach ( $arr as $key => $value ) {
        if (is_array ( $value )) { //Custom handling for arrays
            if ($is_list)
                $parts [] = json_encode2 ( $value ); /* :RECURSION: */
            else
                $parts [] = '"' . $key . '":' . json_encode2( $value ); /* :RECURSION: */
        } else {
            $str = '';
            if (! $is_list)
                $str = '"' . $key . '":';
            //Custom handling for multiple data types
            if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
                $str .= $value; //Numbers
            elseif ($value === false)
            $str .= 'false'; //The booleans
            elseif ($value === true)
            $str .= 'true';
            else
                $str .= '"' . addslashes ( $value ) . '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
            $parts [] = $str;
        }
    }
    $json = implode ( ',', $parts );
    if ($is_list)
        return '[' . $json . ']'; //Return numerical JSON
    return '{' . $json . '}'; //Return associative JSON
}

function chat_Token() {
	if(checkCookie()==1)
	{
		if(!$_SESSION['token'])
		{
			$uid = cookie('uid');
			//	$uid = 1052;
			$user=D('User');
			$map['uid']=$uid;
			$sql=$user->where($map)->find();
			import("@.Util.IMAPI");
			$im = new \IMAPI("sfci50a7ch8oi", "hrXGsSGDzlTi");
			$imgurl=$sql['headimgurl'];
			if(!$imgurl)
				$imgurl='http://'.$_SERVER['SERVER_NAME'].'/Uploads/system/pic01.jpg';
			$res=$im->getToken($uid, $uid, $imgurl);
			$arrRes=json_decode($res,true);
			$_SESSION['token']=$arrRes['token'];
		}
		return $_SESSION['token'];
	}
	else return "";
}

function get_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
	$path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}

function is_weixin() {
	if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) 
	{
		return true;
	}
	return false;
}

function createRandomCode($cls) {
	import("@.Util.IdentifyCode");
	$generate = new \IdentifyCode();
	$code="";
	switch ($cls)
	{
		case 'A' : 
			$code=$generate->createLowcharCode(6);
			break;
		case 'B' : 
			$code=$generate->createRandCode(8);
			break;
		case 'I' :
			$code=$generate->createNumberCode(6);
			break;
		default: $code=$generate->createRandCode(8);break;
	}
	return $code;
}

function resetmenu() {

    $menuList = M('menu')->order('sort desc')->limit('3')->select();

    $post = array();

    $post['button'] = array();

    for($i=0; $i<count($menuList); $i++) {

            $post['button'][$i] = array();

            $menu = $menuList[$i];

            $itemList = M('menuItem')->where('menu_id='.$menu['menu_id'])->order('sort desc')->select();

            $post['button'][$i]['name'] = $menu['menu_name'];

            if(count($itemList) == 0) {

                    $post['button'][$i]['type'] = 'view';

                    $post['button'][$i]['url'] = $menu['target_url'];

            } else {

                    $subArray = array();

                    for($j=0; $j<count($itemList); $j++) {

                            $item = $itemList[$j];

                            $subArray[$j] = array();

                            $subArray[$j]['type'] = 'view';
                            $subArray[$j]['name'] = $item['name'];
                            $subArray[$j]['url'] = $item['target_url'];

                    }

                    $post['button'][$i]['sub_button'] = $subArray;

            }

    }

    return json_encode2($post);

}

function checkCookie() {
	$uid=I('cookie.uid');
	if(!empty($uid))
	{
		return "1";
	}
	else
	{
		return "0";
	}
}

/**
 *
 * @param type $openid
 * @param type $title
 * @param type $content
 * @param type $uri
 * @param type $state
 * @param type $image
 * @return type
 */
function WeNewsMessage($openid, $title, $content, $uri, $state, $image) {

    $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".access_token();
    $post = array(
        "touser" => $openid,
        "msgtype" => "news",
        "news" => array(
            "articles" => array(
                array(
                    'title'=> $title,
                    'description' => $content,
                    //'url' => 'http://'.$_SERVER['HTTP_HOST'].U('message/read?id='.$id),
                    'url' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('appid').'&redirect_uri=http://'.$_SERVER['SERVER_NAME'].$uri.'&response_type=code&scope=snsapi_base&state='.$state.'&connect_redirect=1#wechat_redirect',
                    'picurl' => 'http://'.$_SERVER['HTTP_HOST'].$image,
                ),
            ),
        ),
    );
    $data = json_encode2($post);
    $ay = curl($url,$data);
    $r['date'] = $date;
    $r['post'] = $post;
    $r['json'] = $data;
    $r['state'] = json_decode($ay,true);
    return $r;
}

function WeSend($openid,$content){
    $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".access_token();
    $post = array(
        "touser" => $openid,
        "msgtype" => "text",
        "text" => array(
            "content" => $content,
        ),
    );
    $data = json_encode2($post);
    $ay = curl($url,$data);
    return $ay;
}

function check_wap() {
    if (isset($_SERVER['HTTP_VIA'])) return true;
    if (isset($_SERVER['HTTP_X_NOKIA_CONNECTION_MODE'])) return true;
    if (isset($_SERVER['HTTP_X_UP_CALLING_LINE_ID'])) return true;
    if (strpos(strtoupper($_SERVER['HTTP_ACCEPT']),"VND.WAP.WML") > 0) {
        // Check whether the browser/gateway says it accepts WML.
        $br = "WML";
    } else {
        $browser = isset($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '';
        if(empty($browser)) return true;
        $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');

        $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');

        $found_mobile=checkSubstrs($mobile_os_list,$browser) ||
            checkSubstrs($mobile_token_list,$browser);
        if($found_mobile)
            $br ="WML";
        else $br = "WWW";
    }
    if($br == "WML") {
        return true;
    } else {
        return false;
    }
}

function checkSubstrs($list,$str){
    $flag = false;
    for($i=0;$i<count($list);$i++){
        if(strpos($str,$list[$i]) > 0){
            $flag = true;
            break;
        }
    }
    return $flag;
}

//a为子集 ，b为整集
function isContainArray($a, $b) {

    $c = array_diff($a, $b);
    $flag = empty($c)?1 : 0;

    return $flag;
}

/**
 * 邮件发送函数
 */
function sendMail($to, $title, $content, $attachment="") {

    Vendor('PHPMailer.PHPMailerAutoload');     
    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
    $mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
    $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
    $mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
    $mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
    $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
    $mail->AddAddress($to,"尊敬的客户");
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
    $mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
    $mail->Subject =$title; //邮件主题
    $mail->Body = $content; //邮件内容
    $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示

    //添加附件
    if(!isNullOrEmpty($attachment)) {
        foreach ($attachment as $item) {
            $mail->addAttachment($item['path'], $item['name']);
        }
    }
    
    return($mail->Send());
}

function GetRandStr($len) {
    $chars = array( 
//        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",  
//        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",  
//        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",  
//        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",  
//        "S", "T", "U", "V", "W", "X", "Y", "Z", 
        "0", "1", "2",  
        "3", "4", "5", "6", "7", "8", "9" 
    ); 
    $charsLen = count($chars) - 1; 
    shuffle($chars);   
    $output = ""; 
    for ($i=0; $i<$len; $i++) 
    { 
        $output .= $chars[mt_rand(0, $charsLen)]; 
    }  
    return $output;  
} 

function GetRandAllStr($len) {
    $chars = array( 
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",  
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",  
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",  
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",  
        "S", "T", "U", "V", "W", "X", "Y", "Z", 
        "0", "1", "2",  
        "3", "4", "5", "6", "7", "8", "9" 
    ); 
    $charsLen = count($chars) - 1; 
    shuffle($chars);   
    $output = ""; 
    for ($i=0; $i<$len; $i++) 
    { 
        $output .= $chars[mt_rand(0, $charsLen)]; 
    }  
    return $output;  
}

//循环删除目录和文件函数
function delDirAndFile($dirName) {
	if ($handle = opendir("$dirName")) {
		while (false !== ($item = readdir($handle))) {
			if ($item != "." && $item != "..") {
				if (is_dir("$dirName/$item")) {
					delDirAndFile("$dirName/$item");
				} else {
					unlink("$dirName/$item");
				}
			}
		}
		closedir($handle);
		rmdir($dirName);
	}
}

/**
 * 简单对称加密算法之加密
 * @param String $string 需要加密的字串
 * @param String $skey 加密EKY
 * @author Anyon Zou <zoujingli@qq.com>
 * @date 2013-08-13 19:30
 * @update 2014-10-10 10:10
 * @return String
 */
function encode($string = '', $skey = '4ef530993e8c2db5') {
	$strArr = str_split(base64_encode($string));
	$strCount = count($strArr);
	foreach (str_split($skey) as $key => $value)
		$key < $strCount && $strArr[$key].=$value;
	return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}

/**
 * 简单对称加密算法之解密
 * @param String $string 需要解密的字串
 * @param String $skey 解密KEY
 * @author Anyon Zou <zoujingli@qq.com>
 * @date 2013-08-13 19:30
 * @update 2014-10-10 10:10
 * @return String
 */
function decode($string = '', $skey = '4ef530993e8c2db5') {
	$strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
	$strCount = count($strArr);
	foreach (str_split($skey) as $key => $value)
		$key <= $strCount  && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
	return base64_decode(join('', $strArr));
}

function getModelValidName($str) {
    $array = explode('\\',$str);
    $length = count($array);
    $lastStr = $array[$length-1];
    $validStr = strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $lastStr));
    $validStr = str_replace("_model", "", strtolower($validStr));
    return $validStr;
}

function mapTablePrefixName($tableName) {

    $prefix = $tableName;

    $array = array(
        "account_detail" => "detail",
        "order_disconnect" => "disconnect",
    );

    if(array_key_exists($tableName, $array)) {
        $prefix = $array[$tableName];
    }

    return $prefix . "_id";

}

function getWhereSqlByMap($map) {

    $returnStr = "1=1";

    foreach($map as $key=>$value) {

        $keyArray = explode("-", $key);

        $flag = "eq";

        if(!isNullOrEmpty($keyArray[1])) {
            $flag = $keyArray[1];
        }

        $columnName = str_replace("#", ".", $keyArray[0]);

        switch($flag) {
            case "eq":
                $returnStr .= " and " . $columnName . " = '" . $value . "'";
                break;
            case "leftLike":
                $returnStr .= " and " . $columnName . " like '%" . $value . "'";
                break;
            case "rightLike":
                $returnStr .= " and " . $columnName . " like '" . $value . "%'";
                break;
            case "like":
                $returnStr .= " and " . $columnName . " like '%" . $value . "%'";
                break;
            case "lt":
                $returnStr .= " and " . $columnName . " < '" . $value . "'";
                break;
            case "elt":
                $returnStr .= " and " . $columnName . " <= '" . $value . "'";
                break;
            case "gt":
                $returnStr .= " and " . $columnName . " > '" . $value . "'";
                break;
            case "egt":
                $returnStr .= " and " . $columnName . " >= '" . $value . "'";
                break;
            case "in":
                $returnStr .= " and " . $columnName . " in (" . $value . ")";
                break;
            default:
                break;
        }

    }
    return $returnStr;
}

function isNullOrEmpty($obj) {
    return (!isset($obj) || empty($obj) || $obj == null);
}

function isHaveSpecialChar($str) {
    $chinese=chr(0xa1)."-".chr(0xff);//中文匹配
    $pattern="/^[a-zA-Z0-9($chinese)]{1,}$/";//加上英文、数字匹配

    return !preg_match($pattern,$str);
}

function hiddenName($name) {

    $returnStr = substr($name,0,1) . '***' . substr($name,strlen($name)-1,1);

    return $returnStr;

}

function calculateDayGap($from, $to) {

    $day = ceil(($to-$from)/60/60/24);

    return $day;

}

function createUuid($prefix = ""){    //可以指定前缀
    $str = md5(uniqid(mt_rand(), true));
    $uuid  = substr($str,0,8) . '-';
    $uuid .= substr($str,8,4) . '-';
    $uuid .= substr($str,12,4) . '-';
    $uuid .= substr($str,16,4) . '-';
    $uuid .= substr($str,20,12);
    return $prefix . $uuid;
}

function getCurrentDate() {
    return date('Y-m-d');
}

function getCurrentTime() {
    return date('Y-m-d H:i:s');
}

function toSqlStartTime($time) {
    return $time . ' 00:00:00';
}

function toSqlEndTime($time) {
    return $time . ' 23:59:59';
}

function toSqlIn($str) {
    return '(' . $str . ')';
}

function toSqlLike($str) {
    return '%' . $str . '%';
}

//发送短信（螺丝帽）
function mms($key,$tel,$content){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send.json");

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);

    curl_setopt($ch, CURLOPT_HTTPAUTH , CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD  , 'api:key-'.$key);

    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile' => $tel,'message' => $content.'【education】'));

    $res = curl_exec( $ch );
    curl_close( $ch );
    return $res;
}

//发送短信（其他）
function newmms($tel, $content) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://115.238.169.140:8888/sms.aspx?action=send&userid=207&account=%E7%83%9F%E5%8F%B0%E4%BF%A1%E5%8D%9A&password=a222222&mobile=".$tel."&content=".$content."【佛山医院】&sendTime=&extno=");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    $res = curl_exec( $ch );
    curl_close( $ch );
    //$res  = curl_error( $ch );
    return $res;
}

//获取枚举字符串
function getEnumString($enum, $value) {

    $key = array_search($value, $enum);

    $strKey = $key . '_STRING';

    return $enum[$strKey];

}

//获取枚举下拉列表
function getEnumSelectWidget($enum, $name, $val = 0, $hasAll = 0) {

    $count = count($enum) / 2;
    $index = 0;

    $all = $hasAll == 1 ? '<option value="0">全部</option>' : '';

    $html = '<select class="js-example-basic-single" name=\'' . $name . '\'>' . $all;

    foreach ($enum as $key => $value) {

        if ($count == $index)
            break;

        $selected = '';

        if ($value == $val)
            $selected = 'selected="selected"';

        $html .= '<option value="' . $value . '" ' . $selected . '>' . $enum[$key . '_STRING'] . '</option>';

        $index++;
    }

    $html .= '</select>';

    return $html;
}

//弧度转换
function rad($d) {
    return $d * 3.1415926535898 / 180.0;
}

//计算距离
function getDistance($lat1, $lng1, $lat2, $lng2) {
    $EARTH_RADIUS = 6378.137;
    $radLat1 = rad($lat1);
    //echo $radLat1;
    $radLat2 = rad($lat2);
    $a = $radLat1 - $radLat2;
    $b = rad($lng1) - rad($lng2);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) +
            cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 10000) / 10000;
    return sprintf("%.2f", $s);
}

//转罗马数字
function dec2roman($f)
{
    // Return false if either $f is not a real number, $f is bigger than 3999 or $f is lower or equal to 0:
    if(!is_numeric($f) || $f > 3999 || $f <= 0) return false;

    // Define the roman figures:
    $roman = array('M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1);

    // Calculate the needed roman figures:
    foreach($roman as $k => $v) if(($amount[$k] = floor($f / $v)) > 0) $f -= $amount[$k] * $v;

    // Build the string:
    $return = '';
    foreach($amount as $k => $v)
    {
        $return .= $v <= 3 ? str_repeat($k, $v) : $k . $old_k;
        $old_k = $k;
    }

    // Replace some spacial cases and return the string:
    return str_replace(array('VIV','LXL','DCD'), array('IX','XC','CM'), $return);
}

//array_column
if (!function_exists('array_column')) {
    function array_column($input, $columnKey, $indexKey = null) {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
        $indexKeyIsNull = (is_null($indexKey)) ? true : false;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
        $result = array();
        foreach ((array) $input as $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : null;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    }
}

//重组二维数组
function getKeyIdList($list, $key) {
    return rtrim(implode(',',array_unique(array_filter(array_column($list,$key)))),',');
}

//Json字符串转数组
function convertJsonStringToArray($json) {

    $json = ltrim($json,':');
    $json = str_replace('&quot;', '"', $json);
    $array = json_decode($json,true);

    return $array;

}

//反序列化为数组
function unserializeToArray($str) {

    if(!isNullOrEmpty($str)) {
        $list = unserialize($str);
    } else {
        $list = array();
    }

    return $list;

}